package com.centling.smartSealForPhone.activity

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.constants.UrlConstants
import com.centling.smartSealForPhone.utils.DisplayUtil
import com.centling.smartSealForPhone.utils.OkHttpUtil
import com.centling.smartSealForPhone.utils.ShowToast
import com.google.gson.Gson
import com.jzxiang.pickerview.TimePickerDialog
import com.jzxiang.pickerview.data.Type
import kotlinx.android.synthetic.main.activity_auditor_search.*
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by Jessie 2016/8/17.
 */
class AuditorSearchActivity : TitleBarActivity() {
    var status: String = ""
    var isValid: String = ""
    var category: String = ""
    var reason: String = ""
    private val reasonList = arrayListOf<ApplySealReasonActivity.ApplyReason>()
    private var reasons: ArrayList<String>? = ArrayList()
    var reasonListBean: ApplySealReasonActivity.ReasonListBean? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleBarText("搜索")
        setContentView(R.layout.activity_auditor_search)
        tv_auditor_search.setOnClickListener {
            search()
        }
        tv_auditor_search_cancel.setOnClickListener { clearSearch() }

        clearSearch()
        val itemsValid = arrayOf("--不限--", "正常 ", "换章失效", "解除注册失效")
        val adapterValid = object : ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsValid) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                (view as TextView).textSize = 14f
                return view
            }

            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                view.setPadding(DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f),
                        DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f))
                (view as TextView).textSize = 14f
                return view
            }
        }
        adapterValid.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_auditor_valid.adapter = adapterValid
        sp_auditor_valid.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                when (position) {
                    0 -> isValid = ""
                    1 -> isValid = "0"
                    2 -> isValid = "1"
                    3 -> isValid = "2"
                }
            }
        }
        val itemsCategory = arrayOf("--不限--", "限时", "限次")
        val adapterCategory = object : ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsCategory) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                (view as TextView).textSize = 14f
                return view
            }

            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                view.setPadding(DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f),
                        DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f))
                (view as TextView).textSize = 14f
                return view
            }
        }
        adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_auditor_category.adapter = adapterCategory
        sp_auditor_category.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                when (position) {
                    0 -> category = ""
                    1 -> category = "TIME_LIMIT"
                    2 -> category = "COUNT_LIMIT"
                }
            }
        }
        val items = arrayOf("--不限--", "审核中", "使用中", "审核失败", "未审核过期", "审核成功后过期", "用章完成", "复核成功", "复核失败", "补拍完成", "驳回","驳回过期")
        val adapter = object : ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                (view as TextView).textSize = 14f
                return view
            }

            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                view.setPadding(DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f),
                        DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f))
                (view as TextView).textSize = 14f
                return view
            }
        }
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_auditor_apply.adapter = adapter
        sp_auditor_apply.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                when (position) {
                    0 -> status = ""
                    1 -> status = "0"
                    2 -> status = "1"
                    3 -> status = "2"
                    4 -> status = "3"
                    5 -> status = "4"
                    6 -> status = "5"
                    7 -> status = "6"
                    8 -> status = "7"
                    9 -> status = "8"
                    10 -> status = "9"
                }
            }
        }

        tv_apply_begin_time.setOnClickListener({ v -> showDatePicker(v as TextView) })
        tv_apply_end_time.setOnClickListener({ v -> showDatePicker(v as TextView) })
        tv_first_instance_begin_time.setOnClickListener({ v -> showDatePicker(v as TextView) })
        tv_first_instance_end_time.setOnClickListener({ v -> showDatePicker(v as TextView) })
        tv_review_begin_time.setOnClickListener({ v -> showDatePicker(v as TextView) })
        tv_review_end_time.setOnClickListener({ v -> showDatePicker(v as TextView) })

        sendRequestToFetchApplySealReason()
    }

    fun search() {
        if (!checkInfoToSearch(tv_apply_begin_time, tv_apply_end_time)) {
            return
        }
        if (!checkInfoToSearch(tv_first_instance_begin_time, tv_first_instance_end_time)) {
            return
        }
        if (!checkInfoToSearch(tv_review_begin_time, tv_review_end_time)) {
            return
        }
        startActivity(Intent(this@AuditorSearchActivity, AuditorSearchResultActivity::class.java).putExtra("applicantUserName", et_auditor_user_name.text.toString()).putExtra("sealName", tv_auditor_stamp_name.text.toString()).putExtra("status", status).putExtra("isValid", isValid).putExtra("applyType", category).putExtra("applyReasonType", reason).putExtra("applyTimeStart", tv_apply_begin_time.text.toString()).putExtra("applyTimeEnd", tv_apply_end_time.text.toString()).putExtra("authTimeStart", tv_first_instance_begin_time.text.toString()).putExtra("authTimeEnd", tv_first_instance_end_time.text.toString()).putExtra("reviewTimeStart", tv_review_begin_time.text.toString()).putExtra("reviewTimeEnd", tv_review_end_time.text.toString()).putExtra("isFirst", "3"))

    }

    private fun clearSearch() {
        sp_auditor_apply.setSelection(0)
        sp_auditor_valid.setSelection(0)
        tv_auditor_stamp_name.setText("")
        et_auditor_user_name.setText("")
        sp_auditor_reason.setSelection(0)
        sp_auditor_category.setSelection(0)
        tv_apply_begin_time.text = ""
        tv_apply_end_time.text = ""
        tv_first_instance_begin_time.text = ""
        tv_first_instance_end_time.text = ""
        tv_review_begin_time.text = ""
        tv_review_end_time.text = ""
    }

    private fun showDatePicker(v: TextView) {
        TimePickerDialog.Builder().setCallBack { _, millSeconds ->
            val time = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date(millSeconds))
            v.text = time
        }.setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("请选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(-28800L)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(ContextCompat.getColor(mContext, R.color.blue3))
                .setType(Type.YEAR_MONTH_DAY)
                .setWheelItemTextNormalColor(ContextCompat.getColor(mContext, R.color.grey1))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(mContext, R.color.blue3))
                .setWheelItemTextSize(22)
                .build()
                .show(supportFragmentManager, "year_month_day")

    }

    private fun checkInfoToSearch(v1: TextView, v2: TextView): Boolean {
        if (!TextUtils.equals(v1.text.toString(), "")
                && !TextUtils.equals(v2.text.toString(), "")) {
            var timeBegin = 0L
            var timeEnd = 0L
            val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
            try {
                timeBegin = sdf.parse(v1.text.toString()).time
                timeEnd = sdf.parse(v2.text.toString()).time
            } catch (e: ParseException) {
                e.printStackTrace()
            }

            if (timeBegin > timeEnd) {
                ShowToast.shortTime("开始时间不能大于结束时间")
                return false
            }

        }
        return true
    }

    private fun sendRequestToFetchApplySealReason() {
        getEnqueue(String.format(Locale.CHINA, UrlConstants.FETCH_APPLY_SEAL_REASON, 1), object : OkHttpUtil.NetCallBack {
            override fun onSucceed(json: String?) {
                reasonListBean = Gson().fromJson(json, ApplySealReasonActivity.ReasonListBean::class.java)
                if (reasonListBean != null && reasonListBean!!.typeList != null) {
                    reasonList.addAll(reasonListBean!!.typeList!!)
                    reasons!!.add("--不限--")
                    for (i in 0 until reasonList.size) {
                        reasons!!.add(reasonList[i].name)
                    }

                } else {
                    reasons!!.add("--不限--")
                }
                searchApplyReason()
            }

            override fun onFailed(reason1: String?) {
                //ShowToast.shortTime(reason1)
                searchApplyReason()
            }

        })
    }

    fun searchApplyReason() {

        val array = reasons!!.toArray(arrayOfNulls<String>(reasons!!.size))
        val adapterReason = object : ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, array) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                (view as TextView).textSize = 14f
                return view
            }

            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                view.setPadding(DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f),
                        DisplayUtil.dp2px(16f), DisplayUtil.dp2px(16f))
                (view as TextView).textSize = 14f
                return view
            }
        }
        adapterReason.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_auditor_reason.adapter = adapterReason
        sp_auditor_reason.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                reason = if (position == 0) {
                    ""
                } else {
                    reasons!![position]
                }
            }
        }

    }

}

